<template>
    <van-tabbar v-model="currentIndex" class="vt">
        <van-tabbar-item v-for="item in tabbarData" replace :to="item.path" :icon="item.icon">
            {{ item.title }}
        </van-tabbar-item>
    </van-tabbar>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from "vue-router";

const router = useRouter();
const route = useRoute();

const tabbarData = [
  {
    title: '购买',
    icon: 'shop-o',
    path: '/shop',
  },
  {
    title: '社区',
    icon: 'chat-o',
    path: '/community',
  },
  {
    title: '首页',
    icon: 'https://so1.360tres.com/t013f063fc22ca99ce2.png',
    path: '/home',
  },
  {
    title: '广场',
    icon: 'location-o',
    path: '/square',
  },
  {
    title: "我",
    icon: "user-o",
    path: "/my",
  }
];

let currentIndex = ref(null);

onMounted(() => {
  const storedIndex = sessionStorage.getItem('currentIndex');
  if (storedIndex !== null) {
    currentIndex.value = parseInt(storedIndex, 10);
  } else {
    currentIndex.value = tabbarData.findIndex(item => item.path === route.path);
    if (currentIndex.value === -1) currentIndex.value = 2;
  }
});

// 监听路由变化并更新sessionStorage
router.beforeEach((to, from, next) => {
  sessionStorage.setItem('currentIndex', currentIndex.value);
  next();
});

// 当组件即将卸载时，这里可能不会触发，取决于如何离开应用
onBeforeUnmount(() => {
  sessionStorage.removeItem('currentIndex');
});
</script>

<style scoped>
.vt{
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
}
</style>